import os
import numpy as np
import datetime
import re
import shutil
import tkinter as tk
from tkinter import filedialog
from PIL import ImageTk, Image
from reportlab.pdfgen import canvas
from reportlab.lib.units import mm
from reportlab.lib.pagesizes import letter, landscape

class AEParamChecker:
    def __init__(self):
        self.ABC_SENSOR = ""
        self.result_folder = ""
        self.starttime = datetime.datetime.now()

    def setSavepath(self, path):
        self.result_folder = path
    def setcpppath(self, path):
        self.ABC_SENSOR = path

    def run(self):
        # 在桌面上创建存放检测结果的文件夹
        # desktop_path = os.path.join(os.path.expanduser("~"), 'Desktop')
        # folder_s0_path = os.path.join(self.result_folder, "AE参数检测结果")
        # if not os.path.exists(folder_s0_path):
        #     os.makedirs(folder_s0_path)
        font_name = 'Helvetica'
        flt_normal_thd = "flt_normal_thd"
        flt_ns_thd = "flt_ns_thd"
        HS_BT_thd = "HS_BT_thd"
        TONE_dark_strength = "TONE_dark_strength"
        TONE_bright_strength = "TONE_bright_strength"
        max_lce_gain = "max_lce_gain"
        lv_target = "lv_target"
        max_final_target = "max_final_target"

        def check_interval(c, start_x, start_y, cell_width, cell_height, thdjz, interval, highbound, dz):
            if interval == 0:
                return

            if np.all(thdjz == 0):
                return
            elif np.all(thdjz != 0):
                num1 = 0
                num2 = 0
                for row in thdjz:
                    for element in row:
                        if element > highbound:
                            num1 = num1 + 1

                for row in range(len(thdjz)):
                    for col in range(len(thdjz[row]) - 1):  # 不检查最后一列，
                        if abs(thdjz[row][col] - thdjz[row][col + 1]) > interval:
                            num2 = num2 + 1
                    # 检查行间差值（仅针对矩阵）
                for col in range(len(thdjz[0])):
                    for row in range(len(thdjz) - 1):  # 不检查最后一行
                        if abs(thdjz[row][col] - thdjz[row + 1][col]) > interval:
                            num2 = num2 + 1
                if num1 + num2 == 0:
                    return

                for row_index, row in enumerate(thdjz):
                    y = start_y - (row_index + 1) * cell_height
                    for col_index, value in enumerate(row):
                        x = start_x + col_index * cell_width

                        # 判断当前值是否满足条件（与相邻元素之差大于100）
                        is_red = False
                        if row_index > 0 and abs(value - thdjz[row_index - 1][col_index]) > interval:
                            is_red = True
                        elif row_index < len(thdjz) - 1 and abs(
                                value - thdjz[row_index + 1][col_index]) > interval:
                            is_red = True
                        elif col_index > 0 and abs(value - thdjz[row_index][col_index - 1]) > interval:
                            is_red = True
                        elif col_index < len(row) - 1 and abs(value - thdjz[row_index][col_index + 1]) > interval:
                            is_red = True

                        if is_red or value > highbound:
                            c.setStrokeColorRGB(*red_color)
                            c.setFillColorRGB(*red_color)
                        else:
                            c.setStrokeColorRGB(*normal_color)
                            c.setFillColorRGB(*normal_color)
                        # 设置字体大小和样式
                        c.setFont(font_name, font_size)
                        c.drawString(x, y, str(int(value)))  # 在写入数字
                c.setStrokeColorRGB(*normal_color)
                c.setFillColorRGB(*normal_color)
                c.drawString(100, 550, f"{dz}")  # 写入数字
                c.showPage()

        def check_max(c, start_x, cell_width, thdjz1, thdjz2, thdjz3, highbound1, highbound2, highbound3, dz1, dz2,
                      dz3):
            if np.all(thdjz1 == 0):
                return
            c.setFont(font_name, font_size)
            num1 = 0;
            num2 = 0;
            num3 = 0
            for row in thdjz1:
                if row > highbound1:
                    num1 = num1 + 1
            for row in thdjz2:
                if row > highbound2:
                    num2 = num2 + 1
            for row in thdjz3:
                if row > highbound3:
                    num3 = num3 + 1
            if num1 != 0:
                for col_index, value in enumerate(thdjz1):
                    x = start_x + col_index * cell_width
                    if value > highbound1:
                        c.setStrokeColorRGB(*red_color)
                        c.setFillColorRGB(*red_color)
                    else:
                        c.setStrokeColorRGB(*normal_color)
                        c.setFillColorRGB(*normal_color)
                    y = 500
                    c.drawString(x, y, str(value))  # 写入数字
                c.setStrokeColorRGB(*normal_color)
                c.setFillColorRGB(*normal_color)
                c.drawString(100, 550, dz1)
            if num2 != 0:
                for col_index, value in enumerate(thdjz2):
                    x = start_x + col_index * cell_width
                    if value > highbound2:
                        c.setStrokeColorRGB(*red_color)
                        c.setFillColorRGB(*red_color)
                    else:
                        c.setStrokeColorRGB(*normal_color)
                        c.setFillColorRGB(*normal_color)
                    y = 400
                    c.drawString(x, y, str(value))  # 写入数字
                c.setStrokeColorRGB(*normal_color)
                c.setFillColorRGB(*normal_color)
                c.drawString(100, 450, dz2)
            if num3 != 0:
                for col_index, value in enumerate(thdjz3):
                    x = start_x + col_index * cell_width
                    if value > highbound3:
                        c.setStrokeColorRGB(*red_color)
                        c.setFillColorRGB(*red_color)
                    else:
                        c.setStrokeColorRGB(*normal_color)
                        c.setFillColorRGB(*normal_color)
                    y = 300
                    c.drawString(x, y, str(value))  # 写入数字
                c.setStrokeColorRGB(*normal_color)
                c.setFillColorRGB(*normal_color)
                c.drawString(100, 350, dz3)
            c.showPage()

        def Convert_to_matrix_bz(data):
            data = data.split(",")  # 默认去除空白字符
            data = [element.strip() for element in data]
            data = [int(element) for element in data]
            bmt_thd = np.array(data)
            numbz = bmt_thd.size
            return numbz

        def Convert_to_matrix(data, count_total):
            data = data.split(",")  # 默认去除空白字符
            data = [element.strip() for element in data]
            data = [int(element) for element in data]
            bmt_thd = np.array(data)
            numtbmt = bmt_thd.size
            cn = numtbmt / count_total
            cn = int(cn)
            bmt_thd = np.reshape(bmt_thd, (count_total, cn))
            return bmt_thd

        def get_row_index(bm, BMt):
            FL = bm.split(",")  # 默认去除空白字符
            FL = [element.strip() for element in FL]
            FL = [int(element) for element in FL]
            FL = np.array(FL)
            first_value = FL[0]
            first_value1 = FL[1]
            last_value = FL[-1]
            last_value2 = FL[-2]
            first_value = "{"f"{first_value}"","f"{first_value1}"
            last_value = f"{last_value2}"","f"{last_value}""aaa""}"
            regex_pattern = fr'{first_value}(.*?){last_value}'
            matches = re.findall(regex_pattern, BMt, re.DOTALL)
            count_total = 0
            for match in matches:
                count_total += match.count('aaa')
            return count_total

        # 各个检测函数========================================================================================================
        # 正则表达式==========================================================================================================

        TONE_LCE = r'(?<=\{)\s*(-?\d+)\s*,\s*(-?\d+)\s*,\s*(-?\d+)\s*,\s*(-?\d+)\s*,\s*(-?\d+)\s*,\s*(-?\d+)\s*,\s*(-?\d+)\s*,\s*(-?\d+)\s*,\s*(-?\d+)\s*,' \
                   r'\s*(-?\d+)\s*,\s*(-?\d+)\s*,\s*(-?\d+)\s*,\s*(-?\d+)\s*,\s*(-?\d+)\s*,\s*(-?\d+)\s*,\s*(-?\d+)\s*,\s*(-?\d+)\s*,\s*(-?\d+)\s*,\s*(-?\d+)\s*(?=\})'
        face_AE = r'(?<=\{)' \
                  r'\s*(-?\d+)\s*,\s*(-?\d+)\s*,\s*(-?\d+)\s*,\s*(-?\d+)\s*,\s*(-?\d+)\s*,\s*(-?\d+)\s*,\s*(-?\d+)\s*,\s*(-?\d+)\s*,\s*(-?\d+)\s*,\s*(-?\d+)\s*,' \
                  r'\s*(-?\d+)\s*,\s*(-?\d+)\s*,\s*(-?\d+)\s*,\s*(-?\d+)\s*,\s*(-?\d+)\s*,\s*(-?\d+)\s*,\s*(-?\d+)\s*,\s*(-?\d+)\s*,\s*(-?\d+)\s*,\s*(-?\d+)\s*,' \
                  r'\s*(-?\d+)\s*,\s*(-?\d+)\s*,\s*(-?\d+)\s*,\s*(-?\d+)\s*,\s*(-?\d+)\s*,\s*(-?\d+)\s*,\s*(-?\d+)\s*,\s*(-?\d+)\s*,\s*(-?\d+)\s*,\s*(-?\d+)\s*,' \
                  r'\s*(-?\d+)\s*,\s*(-?\d+)\s*,\s*(-?\d+)\s*,\s*(-?\d+)\s*,\s*(-?\d+)\s*,\s*(-?\d+)\s*,\s*(-?\d+)\s*,\s*(-?\d+)\s*,\s*(-?\d+)\s*,\s*(-?\d+)\s*,' \
                  r'\s*(-?\d+)\s*,\s*(-?\d+)\s*,\s*(-?\d+)\s*,\s*(-?\d+)\s*,\s*(-?\d+)\s*,\s*(-?\d+)\s*,\s*(-?\d+)\s*,\s*(-?\d+)\s*,\s*(-?\d+)\s*,\s*(-?\d+)\s*,' \
                  r'\s*(-?\d+)\s*,\s*(-?\d+)\s*,\s*(-?\d+)\s*,\s*(-?\d+)\s*,\s*(-?\d+)\s*,\s*(-?\d+)\s*,\s*(-?\d+)\s*,\s*(-?\d+)\s*,\s*(-?\d+)\s*,\s*(-?\d+)\s*,' \
                  r'\s*(-?\d+)\s*,\s*(-?\d+)\s*,\s*(-?\d+)\s*,\s*(-?\d+)\s*,\s*(-?\d+)\s*,\s*(-?\d+)\s*,\s*(-?\d+)\s*,\s*(-?\d+)\s*,\s*(-?\d+)\s*,\s*(-?\d+)\s*,' \
                  r'\s*(-?\d+)\s*,\s*(-?\d+)\s*,\s*(-?\d+)\s*,\s*(-?\d+)\s*,\s*(-?\d+)\s*,\s*(-?\d+)\s*,\s*(-?\d+)\s*,\s*(-?\d+)\s*,\s*(-?\d+)\s*,\s*(-?\d+)\s*,' \
                  r'\s*(-?\d+)\s*,\s*(-?\d+)\s*,\s*(-?\d+)\s*,\s*(-?\d+)\s*,\s*(-?\d+)\s*,\s*(-?\d+)\s*,\s*(-?\d+)\s*,\s*(-?\d+)\s*,\s*(-?\d+)\s*,\s*(-?\d+)\s*,' \
                  r'\s*(-?\d+)\s*,\s*(-?\d+)\s*,\s*(-?\d+)\s*,\s*(-?\d+)\s*,\s*(-?\d+)\s*,\s*(-?\d+)\s*,\s*(-?\d+)\s*,\s*(-?\d+)\s*,\s*(-?\d+)\s*,\s*(-?\d+)\s*,' \
                  r'(?=\})'

        # 正则表达式==========================================================================================================

        # 取出输入框的信息=====================================================================================================
        maxflt = 1500
        intervalfltns = 200
        intervalflt = 200
        maxlce = 512
        intervallce = 200
        intervalBT = 800
        maxbt = 4096
        maxmt = 4096
        intervalMT = 400
        maxmlgain = 416
        maxlvtarget = 2400
        maxfinaltarget = 2500

        # 取出输入框的信息=====================================================================================================

        # 导入效果参数文件夹地址
        search_dir = self.ABC_SENSOR

        # AE.cpp文件的参数===================================================================================================
        # 指定要查找的文件类型列表
        flt_northd = 0
        flt_northd = 0
        flt_nsthd = 0
        bt_thd = 0
        mt_thd = 0
        LVTarget = 0
        MaxLceGain = 0
        MaxFinalTarget = 0
        Dark_Strength = 0
        Bright_Strength = 0
        for root, dirs, files in os.walk(search_dir):
            # 在当前目录下查找 AE.cpp 和 tone.cpp 文件
            current_folder_name = os.path.basename(root)
            pdf_file_path = os.path.join(self.result_folder, f"AE.pdf")
            # print(parent_directory_AETONE)
            c = canvas.Canvas(pdf_file_path)
            # 设置字体和颜色
            c.setFillColorRGB(1, 0, 0)  # 红色（RGB：255, 0, 0）
            c.setFont(font_name, 12)  # 使用注册过的中文字体名称
            c.setPageSize(landscape(letter))
            normal_color = (0, 0, 0)  # 黑色
            red_color = (1, 0, 0)  # 红色
            font_size = 10
            c.setFont(font_name, font_size)
            cell_width = 10 * mm
            cell_height = 10 * mm
            start_x = 20 * mm
            start_y = letter[1] - cell_height - 100 * mm  # 从底部开始向上排列

            for filename in files:
                ae_file_path = ""
                tone_file_path = ""

                if filename == 'AE.txt':
                    ae_file_path = os.path.join(root, filename)
                elif filename == 'TONE.txt':
                    tone_file_path = os.path.join(root, filename)

                if ae_file_path != "":
                    with open(ae_file_path, 'r', encoding='gbk', errors='replace') as file:
                        AE = file.read()
                    AE1 = re.sub(r'/.*?\n', '\n', AE, flags=re.MULTILINE)
                    AE2 = re.sub(r'^\s+|\s+$', '', AE1, flags=re.MULTILINE)
                    AE3 = re.sub(r'\n', '', AE2)
                    # 用正则表达式搜索FLT的thd矩阵==============================
                    matches_face = re.findall(face_AE, AE3)
                    results_face = []
                    for match_face in matches_face:
                        results_face.append(list(map(int, match_face)))
                    flt_northd = results_face[8]
                    flt_nsthd = results_face[11]
                    flt_northd = np.array(flt_northd)
                    flt_northd = np.reshape(flt_northd, (10, 10))
                    flt_nsthd = np.array(flt_nsthd)
                    flt_nsthd = np.reshape(flt_nsthd, (10, 10))

                    # 取出BT NT
                    matches_hs = re.findall(r'\{(\d+(?:,\s*\d+)*)(?:,?)\}', AE3)
                    bzsz = matches_hs[15]
                    bz = Convert_to_matrix_bz(bzsz)
                    if bz == 6:
                        bt = matches_hs[34]
                        mt = matches_hs[36]
                    elif bz == 28:
                        bt = matches_hs[35]
                        mt = matches_hs[37]

                    AEBM = re.sub(r'\n\s*\n', '\n', AE1)
                    AEBM = re.sub(r'^\s+|\s+$', '', AEBM, flags=re.MULTILINE)
                    AEBMt = AEBM.replace(",\n", "aaa")
                    AEBMt = re.sub(r'\n', '', AEBMt)
                    AEBMt = AEBMt.replace(" ", "")

                    count_total_bt = get_row_index(bt, AEBMt)
                    count_total_bt = int(count_total_bt)
                    count_total_bt = count_total_bt + 1
                    # print(count_total_bt)
                    count_total_mt = get_row_index(mt, AEBMt)
                    count_total_mt = int(count_total_mt)
                    count_total_mt = count_total_mt + 1
                    # print(count_total_mt)
                    bt_thd = Convert_to_matrix(bt, count_total_bt)
                    mt_thd = Convert_to_matrix(mt, count_total_mt)

                if tone_file_path != "":
                    with open(tone_file_path, 'r') as file:
                        TONE = file.read()
                    matches = re.findall(TONE_LCE, TONE)
                    results = []
                    for match in matches:
                        results.append(list(map(int, match)))
                    LVTarget = results[0]  #
                    MaxLceGain = results[1]  #
                    MaxFinalTarget = results[2]  #
                    Dark_Strength = results[3:13]  #
                    Bright_Strength = results[14:24]  #
                    LVTarget = np.array(LVTarget)
                    MaxLceGain = np.array(MaxLceGain)
                    MaxFinalTarget = np.array(MaxFinalTarget)
                    Dark_Strength = np.array(Dark_Strength)
                    Bright_Strength = np.array(Bright_Strength)
                    # print(Dark_Strength)
            check_interval(c, start_x, start_y, cell_width, cell_height, flt_northd, intervalflt, 4096, flt_normal_thd)
            check_interval(c, start_x, start_y, cell_width, cell_height, flt_nsthd, intervalflt, 4096, flt_ns_thd)
            check_interval(c, start_x, start_y, cell_width, cell_height, bt_thd, intervalBT, maxbt, HS_BT_thd)
            check_interval(c, start_x, start_y, cell_width, cell_height, mt_thd, intervalMT, maxmt, HS_BT_thd)
            check_interval(c, start_x, start_y, cell_width, cell_height, Dark_Strength, intervallce, maxlce,
                           TONE_dark_strength)
            check_interval(c, start_x, start_y, cell_width, cell_height, Bright_Strength, intervallce, maxlce,
                           TONE_bright_strength)
            check_max(c, start_x, cell_width, LVTarget, MaxLceGain, MaxFinalTarget, maxlvtarget, maxmlgain,
                      maxfinaltarget, lv_target, max_lce_gain, max_final_target)

            c.save()
            flt_northd = int(0)
            flt_nsthd = int(0)
            bt_thd = int(0)
            mt_thd = int(0)
            LVTarget = int(0)
            MaxLceGain = int(0)
            MaxFinalTarget = int(0)
            Dark_Strength = int(0)
            Bright_Strength = int(0)

        # TONE.cpp文件的参数=================================================================================================
        # 判断是否所有参数都收敛=================================================================================================

        def delete_small_pdf_files(directory, min_size_kb=2.5):
            for filename in os.listdir(directory):
                if filename.endswith('.pdf'):
                    filepath = os.path.join(directory, filename)
                    size_in_bytes = os.path.getsize(filepath)

                    # 判断文件大小是否小于5KB（转换为字节）
                    if size_in_bytes < min_size_kb * 1024:
                        os.remove(filepath)

        delete_small_pdf_files(self.result_folder)
        pdf_files = [f for f in os.listdir(self.result_folder) if f.endswith('.pdf')]
        if not pdf_files:

            pdf_file_path = os.path.join(self.result_folder, "Check result.pdf")
            font_name = 'Helvetica'  # 替换为实际存在的中文字体文件名
            # font_path = 'C:/Users/qilin.lv/PycharmProjects/pythonProject1/data-p/heiti.ttf'  # 替换为中文字体.ttf文件的实际路径
            # custom_font = TTFont(font_name, font_path)
            # pdfmetrics.registerFont(custom_font)
            # font_name = 'Helvetica'
            c = canvas.Canvas(pdf_file_path)
            # page_size = c.pagesize
            # page_width, page_height = page_size
            c.setFont(font_name, 10)  # 使用注册过的中文字体名称
            AA = [f"{search_dir} is smooth", "check standard(00 indicates that no check):",
                  f"Flt_Normal_Thd---difference value between adjacent elements:{intervalflt}",
                  f"Flt_NS_Thd---difference value between adjacent elements:{intervalfltns}",
                  f"HS_BT_thd---Maximum limit:{maxbt}",
                  f"HS_BT_thd---difference value between adjacent elements:{intervalBT}",
                  f"HS_MT_thd---Maximum limit:{maxmt}",
                  f"HS_MT_thd---difference value between adjacent elements:{intervalMT}",
                  f"lce_strength---Maximum limit:{maxlce}",
                  f"lce_strength---difference value between adjacent elements:{intervallce}",
                  f"MaxLceGain---Maximum limit:{maxmlgain}",
                  f"LVTarget---Maximum limit:{maxlvtarget}",
                  f"MaxFinalTarget---Maximum limit:{maxfinaltarget}"]
            line_height = 40
            current_y = 800 - line_height
            for string in AA:
                current_y -= line_height
                c.drawString(20, current_y, string)  # (x, y) 是文本左下角的位置
            # c.showPage()
            c.save()

        # endtime = datetime.datetime.now()
        # current_folder_name = os.path.basename(root)
        # print(f"[{current_folder_name}]:AE_Check Done！运行时间: {endtime - self.starttime}\n")




        # def manage_pdf_files(search_dir):
        #     has_ae_pdf = False
        #     has_checkresult_pdf = False
        #     checkresult_files = []
        #
        #     # 遍历目录，检查PDF文件类型
        #     for root, dirs, files in os.walk(search_dir):
        #         for filename in files:
        #             if filename.lower() == 'ae.pdf':
        #                 has_ae_pdf = True
        #             elif filename.endswith('Check result.pdf'):
        #                 has_checkresult_pdf = True
        #                 checkresult_files.append(os.path.join(root, filename))
        #
        #
        #     # 如果全为CheckResult.pdf
        #     if has_ae_pdf:
        #         for file in checkresult_files:
        #             print(f"Removing file: {file}")
        #             os.remove(file)
        #         print("Both AE.pdf and CheckResult.pdf exist. Removed all CheckResult.pdf files.")
        #     # 如果全为CheckResult.pdf
        #     elif has_checkresult_pdf:
        #         ae_folder_path = os.path.join(self.result_folder, 'AE结果')
        #         os.makedirs(ae_folder_path, exist_ok=True)
        #         for file in checkresult_files:
        #             shutil.copy(file, ae_folder_path)
        #         print(f"Saved all CheckResult.pdf files to {ae_folder_path}")
        #
        # manage_pdf_files(self.result_folder)

#
# if __name__ == "__main__":
#     checker = AEParamChecker()
#     checker.run()